<?php 
namespace app\index\model;
use think\Model;
use think\Session;
use think\Db;
class Login_model extends Model
{

    //登陆
	public function login($params)
	{
		$where = array (															
            'username'=>$params['username'],
        );
        $sql = Db::table('user')->where($where)->find();
        if($sql) {	
		}else{
			echo "<script> alert('用户名输入错误');location.href='login';</script>";die;
		}
     	$num=$sql['count'];
        //锁定
        if(time()-$sql['error_time']>1*3600)					//锁定1小时
        {  
            $num = 3;											//一小时后恢复默认登陆次数,3次
            $count=array(
            	'count'=>$num
            );
            Db::table('user')->where($where)->setField($count);
        }

        //密码错误
        if($num==0)
        {
          echo "<script> alert('密码输入次数过多,已锁定');location.href='login';</script>";die;
        }
        
        $params['password'] = md5($params['password']);
        //验证密码
     	if($params['password']!=$sql['password'])
        {
        	if($num == 0){
        	}else{
        		$num=($num-1);
        	}
            $time=time();
	        $linshi['count'] = $num;
	        $linshi['error_time'] = $time;
			$list = Db::table("user")->where('user_id',$sql['user_id'])->setField($linshi);
			if ($list) {
				echo "<script> alert('密码输入错误');location.href='login';</script>";die;
			}
        }

        //成功
        $num=3;
		$linshi['count'] = $num;
		$list = Db::table('user')->where('user_id',$sql['user_id'])->setField($linshi); 
		Session::set('username',$sql['username']);   
     	Session::set('admin',$sql['admin']);  
		return $list;
	}


    //注册
    public function registered($params)
    {
        if (empty($params['username']))
        {
            echo "<script> alert('请输入用户名');location.href='registered';</script>";die;
        }
        if (empty($params['password']))
        {
            echo "<script> alert('请输入密码');location.href='registered';</script>";die;
        }
        $where = array (                                                            
            'username'=>$params['username'],
        );
        $sql = Db::table('user')->where($where)->find();
        if($sql) {  
            echo "<script> alert('用户名已存在');location.href='registered';</script>";die;
        }
        $data['username'] = $params['username'];
        $data['password'] = md5($params['password']);
        $registered = Db::table('user')->insert($data);
        return $registered;
    }
}